package com.jack.lib.net

import com.jack.lib.core.net.*
import com.jack.lib.core.utils.JLog
import com.jack.lib.net.cache.Cache
import com.jack.lib.net.loading.Loading
import kotlinx.coroutines.*
import okhttp3.internal.notifyAll
import okhttp3.internal.wait

/**
 * author : chong.huang
 * create : 2022/3/22
 * desc   :
 */
class ParamImpl<T, J: JBaseData<T>>(private val param: JNetParam<T, J>) : IParam<T, J> {

    override fun onSuccess(onNext: (T?) -> Unit): IParam<T, J> {
        return apply { param.onNext = onNext }
    }

    override fun onFailed(onFail: (J) -> Unit): IParam<T, J> {
        return apply { param.onFail = onFail }
    }

    override fun onError(onError: (cause: Throwable) -> Unit): IParam<T, J> {
        return apply { param.onError = onError }
    }

    override fun onComplete(onComplete: () -> Unit): IParam<T, J> {
        return apply { param.onComplete = onComplete }
    }

    override fun onCancel(onCancel: () -> Unit): IParam<T, J> {
        return apply { param.onComplete = onCancel }
    }

    override fun loadingMode(loadingMode: NetLoadingMode): IParam<T, J> {
        return apply { param.loading = Loading.obtain(loadingMode, param.view) }
    }

    override fun dispatchMode(dispatchMode: NetDispatchMode): IParam<T, J> {
        return apply { param.dispatchMode = dispatchMode }
    }

    override fun cacheMode(cacheMode: NetCacheStrategy): IParam<T, J> {
        return apply { param.cache = Cache.obtain(cacheMode, param.ktApi.hashCode()) }
    }

    override fun catchError(): IParam<T, J> {
        return apply { param.catchError = false }
    }

    override suspend fun get(): NetResult<T, J> {
        param.job?.cancel()
        JNet.networkHandler(param)
        return param.result
    }

}